@model List<MVCWeekOne.Models.AccountDTO>
@{
    ViewData["Title"] = "用户管理";
}

<style>
    /* 移除所有遮罩层 */
    .layui-layer-shade {
        display: none !important;
    }

    /* 确保弹窗可以正常交互 */
    .layui-layer {
        z-index: 9999 !important;
    }

    /* 确保弹窗内容可以正常点击 */
    .layui-layer-content {
        pointer-events: auto !important;
    }

    /* 移除任何可能的遮罩效果 */
    .layui-layer-shade,
    .layui-layer-shade[layui-layer-shade] {
        background: none !important;
        opacity: 0 !important;
        display: none !important;
    }

    /* 确保按钮可以正常点击 */
    .layui-btn {
        pointer-events: auto !important;
        cursor: pointer !important;
        z-index: 10000 !important;
    }

    /* 确保表单元素可以正常交互 */
    .layui-form-item input,
    .layui-form-item select,
    .layui-form-item button {
        pointer-events: auto !important;
        z-index: 10000 !important;
    }

    /* 表格自适应样式 */
    .layui-card-body {
        padding: 15px;
        height: calc(100vh - 200px);
        overflow: hidden;
    }

    #userTable {
        width: 100% !important;
    }

    .layui-table-view {
        height: 100% !important;
    }

    .layui-table-main {
        height: calc(100% - 40px) !important;
    }

    /* 确保表格容器铺满 */
    .layui-card {
        height: 100%;
        margin: 0;
    }

    /* 隐藏页面底部的错误提示信息 */
    .layui-form-danger,
    .layui-text-danger,
    .layui-form-msg {
        display: none !important;
    }

    /* 隐藏任何可能的验证消息 */
    .layui-form-msg,
    .layui-form-danger,
    .layui-text-danger,
    .layui-form-msg-danger {
        display: none !important;
    }

    /* 确保查询表单不显示验证消息 */
    #searchForm .layui-form-msg,
    #searchForm .layui-form-danger,
    #searchForm .layui-text-danger {
        display: none !important;
    }
</style>

<div class="layui-card">
    <div class="layui-card-header">
        <div class="layui-row">
            <div class="layui-col-md6">
                <h3>用户管理</h3>
            </div>
            <div class="layui-col-md6" style="text-align: right;">
                <button class="layui-btn" id="addUserBtn">添加用户</button>
            </div>
        </div>
    </div>
    <div class="layui-card-body">
        <!-- 查询条件 -->
        <form class="layui-form" id="searchForm">
            <div class="layui-row layui-col-space10">
                <div class="layui-col-md4">
                    <div class="layui-form-item">
                        <label class="layui-form-label">用户名</label>
                        <div class="layui-input-block">
                            <input type="text" name="Name" placeholder="请输入用户名" class="layui-input">
                        </div>
                    </div>
                </div>
                <div class="layui-col-md4">
                    <div class="layui-form-item">
                        <div class="layui-input-block">
                            <button type="button" class="layui-btn" id="searchBtn">查询</button>
                            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                        </div>
                    </div>
                </div>
            </div>
        </form>

        <!-- 用户列表 -->
        <table class="layui-table" id="userTable" lay-filter="userTable">
            <!-- 移除HTML表头，让Layui完全通过JavaScript渲染 -->
        </table>

        <!-- 分页 -->
        <div id="userPager"></div>
    </div>
</div>

<!-- 状态模板 -->
<script type="text/html" id="stateTpl">
    {{# if(d.isState) { }}
        <span class="layui-badge layui-bg-green">启用</span>
    {{# } else { }}
        <span class="layui-badge layui-bg-gray">禁用</span>
    {{# } }}
</script>

<!-- 角色名称模板 -->
<script type="text/html" id="roleNameTpl">
    {{# if(d.roleName && d.roleName.length > 0) { }}
        {{d.roleName.join(', ')}}
    {{# } else { }}
        <span class="layui-text-gray">无角色</span>
    {{# } }}
</script>

<!-- 操作模板 -->
<script type="text/html" id="operationTpl">
     <button class="layui-btn layui-btn-xs" onclick="editUser('{{d.id}}')">编辑</button>
     <button class="layui-btn layui-btn-xs layui-btn-danger" onclick="deleteUser('{{d.id}}')">删除</button>
 </script>

<!-- 添加用户弹窗 -->
<div id="addUserModal" style="display: none; padding: 20px;">
    <form class="layui-form" id="addUserForm" lay-filter="addUserForm">
        <div class="layui-form-item">
            <label class="layui-form-label">用户名</label>
            <div class="layui-input-block">
                <input type="text" name="Name" required lay-verify="required" placeholder="请输入用户名" class="layui-input"
                    autocomplete="off">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">密码</label>
            <div class="layui-input-block">
                <input type="password" name="Pwd" required lay-verify="required" placeholder="请输入密码" class="layui-input"
                    autocomplete="off">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">真实姓名</label>
            <div class="layui-input-block">
                <input type="text" name="RealName" required lay-verify="required" placeholder="请输入真实姓名"
                    class="layui-input" autocomplete="off">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">角色</label>
            <div class="layui-input-block">
                <select name="RoleIds" lay-verify="required" id="roleSelect" lay-filter="roleSelect">
                    <option value="">请选择角色</option>
                </select>
            </div>
        </div>

        <div class="layui-form-item">
            <div class="layui-input-block">
                <button type="button" class="layui-btn" lay-submit lay-filter="addUserSubmit">提交</button>
                <button type="button" class="layui-btn layui-btn-primary" id="resetBtn">重置</button>
            </div>
        </div>
    </form>
</div>

<!-- 编辑用户弹窗 -->
<div id="editUserModal" style="display: none; padding: 20px;">
    <form class="layui-form" id="editUserForm" lay-filter="editUserForm">
        <input type="hidden" name="Id" id="editUserId">
        <div class="layui-form-item">
            <label class="layui-form-label">用户名</label>
            <div class="layui-input-block">
                <input type="text" name="Name" required lay-verify="required" placeholder="请输入用户名" class="layui-input"
                    autocomplete="off">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">密码</label>
            <div class="layui-input-block">
                <input type="text" name="Pwd" placeholder="密码不可修改" class="layui-input" readonly
                    style="background-color: #f5f5f5; color: #999;">
                <input type="hidden" name="RealPwd" id="realPassword">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">真实姓名</label>
            <div class="layui-input-block">
                <input type="text" name="RealName" required lay-verify="required" placeholder="请输入真实姓名"
                    class="layui-input" autocomplete="off">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">角色</label>
            <div class="layui-input-block">
                <select name="RoleIds" lay-verify="required" id="editRoleSelect" lay-filter="editRoleSelect">
                    <option value="">请选择角色</option>
                </select>
            </div>
        </div>

        <div class="layui-form-item">
            <div class="layui-input-block">
                <button type="button" class="layui-btn" lay-submit lay-filter="editUserSubmit">更新</button>
                <button type="button" class="layui-btn layui-btn-primary" id="editResetBtn">重置</button>
            </div>
        </div>
    </form>
</div>

@section Scripts {
    <script>
        // 等待Layui完全加载后再执行
        layui.use(['table', 'form', 'layer', 'laypage'], function () {
            var table = layui.table;
            var form = layui.form;
            var layer = layui.layer;
            var laypage = layui.laypage;

            console.log('Layui模块加载完成');

            // Layui模块加载完成，开始初始化用户管理页面

            // 初始化用户表格
            initUserTable(table, layer);

            // 查询按钮点击事件
            $('#searchBtn').click(function () {
                var searchData = {};
                $('#searchForm').serializeArray().forEach(function (item) {
                    if (item.value) {
                        searchData[item.name] = item.value;
                    }
                });
                loadUserData(1, searchData, table);
            });

            // 加载角色数据
            loadRoles();

            // 添加用户按钮点击事件
            $('#addUserBtn').click(function () {
                console.log('点击添加用户按钮');

                // 先加载角色数据，然后打开弹窗
                loadRoles().then(function () {
                    var layerIndex = layer.open({
                        type: 1,
                        title: '添加用户',
                        area: ['500px', '450px'],
                        content: $('#addUserModal'),
                        shade: false, // 完全移除遮罩层
                        shadeClose: false,
                        maxmin: false,
                        closeBtn: 1, // 显示关闭按钮
                        success: function (layero, index) {
                            // 弹窗打开后重新渲染表单
                            layui.form.render();

                            // 清除任何可能的验证消息
                            $('.layui-form-msg, .layui-form-danger, .layui-text-danger').remove();

                            // 确保弹窗内容可以交互
                            $(layero).find('input, select, button').prop('disabled', false);

                            // 阻止事件冒泡
                            $(layero).on('click', function (e) {
                                e.stopPropagation();
                            });

                            // 直接绑定提交按钮事件
                            $(layero).find('button[lay-submit]').on('click', function (e) {
                                e.preventDefault();
                                e.stopPropagation();
                                handleFormSubmitDirect();
                            });

                            // 绑定重置按钮事件
                            $(layero).find('#resetBtn').on('click', function (e) {
                                e.preventDefault();
                                e.stopPropagation();
                                // 清空表单
                                $('#addUserForm')[0].reset();
                                // 清除验证消息
                                $('.layui-form-msg, .layui-form-danger, .layui-text-danger').remove();
                                // 重新渲染表单
                                layui.form.render();
                                layer.msg('表单已重置', { icon: 1 });
                            });

                            // 聚焦到第一个输入框
                            setTimeout(function () {
                                $('#addUserForm input[name="Name"]').focus();
                            }, 100);
                        },
                        end: function () {
                            // 弹窗关闭后清空表单
                            $('#addUserForm')[0].reset();
                            // 清除所有验证消息
                            $('.layui-form-msg, .layui-form-danger, .layui-text-danger').remove();
                            layui.form.render();
                        }
                    });

                }).catch(function (error) {
                    layer.msg('加载角色数据失败: ' + error, { icon: 2 });
                });
            });

            // 表单提交事件监听
            $(document).on('click', '.layui-btn[lay-submit]', function (e) {
                e.preventDefault();
                e.stopPropagation();
                handleFormSubmitDirect();
            });

            // 在Layui模块内部定义处理函数
            function handleFormSubmitDirect() {
                console.log('开始处理表单提交');

                // 获取表单数据
                var formData = {
                    Name: $('#addUserForm input[name="Name"]').val(),
                    Pwd: $('#addUserForm input[name="Pwd"]').val(),
                    RealName: $('#addUserForm input[name="RealName"]').val(),
                    RoleIds: $('#addUserForm select[name="RoleIds"]').val()
                };


                // 处理roleId，将字符串转换为数组
                var roleId = [];
                if (formData.RoleIds) {
                    roleId.push(parseInt(formData.RoleIds));
                }

                // 构建提交数据 - 根据API文档，参数名应该是小写
                var submitData = {
                    name: formData.Name,
                    pwd: formData.Pwd,
                    realName: formData.RealName,
                    roleId: roleId
                };

                var loadIndex = layer.load(1, {
                    shade: [0.1, '#fff']
                });



                $.ajax({
                    url: '@Url.Action("AddUser", "Account")',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(submitData),
                    success: function (res) {
                        layer.close(loadIndex);

                        if (res.success) {
                            layer.msg(res.message, { icon: 1 });
                            layer.closeAll();
                            // 重新加载表格数据
                            table.reload('userTable');
                        } else {
                            layer.msg(res.message || '添加失败', { icon: 2 });
                        }
                    },
                    error: function (xhr, status, error) {
                        layer.close(loadIndex);
                        console.error('提交失败:', xhr.responseText);
                        console.error('状态码:', xhr.status);
                        console.error('错误信息:', error);
                        layer.msg('网络错误，请稍后重试', { icon: 2 });
                    }
                });
            }
        });

        // 初始化用户表格
        function initUserTable(table, layer) {
            // 开始初始化用户表格

            table.render({
                elem: '#userTable',
                url: '@Url.Action("GetUserPage", "Account")',

                method: 'get',
                where: getSearchParams(),
                page: true,
                limit: 10,
                limits: [10, 20, 50, 100],
                height: 'full-220',
                parseData: function (res) {
                    return {
                        "code": res.code,
                        "msg": res.msg,
                        "count": res.count,
                        "data": res.data
                    };
                },
                cols: [[
                    { type: 'numbers', title: '序号', width: 80, fixed: 'left' },
                    { field: 'name', title: '用户名', minWidth: 120 },
                    { field: 'realName', title: '真实姓名', minWidth: 120 },
                    { field: 'roleName', title: '角色', minWidth: 150, templet: '#roleNameTpl' },
                    { field: 'isState', title: '状态', width: 100, templet: '#stateTpl' },
                    {
                        field: 'createTime', title: '创建时间', minWidth: 160, sort: true, templet: function (d) {
                            if (!d.createTime) return '';
                            var date = new Date(d.createTime);
                            var year = date.getFullYear();
                            var month = String(date.getMonth() + 1).padStart(2, '0');
                            var day = String(date.getDate()).padStart(2, '0');
                            var hours = String(date.getHours()).padStart(2, '0');
                            var minutes = String(date.getMinutes()).padStart(2, '0');
                            var seconds = String(date.getSeconds()).padStart(2, '0');
                            return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds;
                        }
                    },
                    { field: 'operation', title: '操作', width: 150, templet: '#operationTpl', fixed: 'right' }
                ]],
                done: function (res, curr, count) {

                    if (res.code !== 0) {
                        console.error('API返回错误:', res.msg);
                        layer.msg('获取数据失败: ' + res.msg, { icon: 2 });
                    } else {
                        console.log('API调用成功，数据条数:', res.data ? res.data.length : 0);
                    }
                },
                error: function (res) {
                    console.error('表格加载失败:', res);
                    layer.msg('表格加载失败', { icon: 2 });
                }
            });
        }

        // 获取查询参数
        function getSearchParams() {
            var params = {};
            $('#searchForm').serializeArray().forEach(function (item) {
                if (item.value) {
                    params[item.name] = item.value;
                }
            });
            return params;
        }

        // 加载用户数据
        function loadUserData(page, params, table) {
            table.reload('userTable', {
                where: params,
                page: {
                    curr: page
                }
            });
        }

        // 加载角色数据
        function loadRoles() {
            return new Promise(function (resolve, reject) {
                $.ajax({
                    url: '@Url.Action("GetRoles", "Account")',
                    type: 'GET',
                    success: function (res) {
                        if (res.success) {
                            var roleSelect = $('#roleSelect');
                            roleSelect.empty();
                            roleSelect.append('<option value="">请选择角色</option>');

                            res.data.forEach(function (role) {
                                roleSelect.append('<option value="' + role.id + '">' + role.roleName + '</option>');
                            });

                            layui.form.render('select');
                            resolve(); // 成功则resolve
                        } else {
                            reject('加载角色失败: ' + res.message); // 失败则reject
                        }
                    },
                    error: function () {
                        reject('加载角色失败，网络错误');
                    }
                });
            });
        }

        // 编辑用户
        function editUser(userId) {
            console.log('编辑用户ID:', userId, '类型:', typeof userId);

            // 确保userId是数字类型
            if (typeof userId === 'string') {
                userId = parseInt(userId);
            }

            // 先加载角色数据，然后获取用户信息并打开编辑弹窗
            loadRoles().then(function () {
                // 获取用户信息
                $.ajax({
                    url: '@Url.Action("GetUserById", "Account")',
                    type: 'GET',
                    data: { userId: userId },
                    success: function (res) {
                        console.log('获取用户信息响应:', res);
                        console.log('用户数据详情:', res.data);
                        if (res.success) {
                            openEditUserModal(res.data);
                        } else {
                            layer.msg(res.message || '获取用户信息失败', { icon: 2 });
                        }
                    },
                    error: function (xhr, status, error) {
                        console.error('获取用户信息失败:', xhr.responseText);
                        layer.msg('获取用户信息失败', { icon: 2 });
                    }
                });
            }).catch(function (error) {
                layer.msg('加载角色数据失败: ' + error, { icon: 2 });
            });
        }

        // 打开编辑用户弹窗
        function openEditUserModal(userData) {
            var layerIndex = layer.open({
                type: 1,
                title: '编辑用户',
                area: ['500px', '450px'],
                content: $('#editUserModal'),
                shade: false,
                shadeClose: false,
                maxmin: false,
                closeBtn: 1,
                success: function (layero, index) {
                    // 弹窗打开后重新渲染表单
                    layui.form.render();

                    // 清除任何可能的验证消息
                    $('.layui-form-msg, .layui-form-danger, .layui-text-danger').remove();

                    // 填充表单数据
                    $('#editUserId').val(userData.id);
                    $('#editUserForm input[name="Name"]').val(userData.name);
                    $('#editUserForm input[name="Pwd"]').val('********'); // 显示星号
                    $('#realPassword').val(userData.pwd); // 保存真实密码到隐藏字段
                    $('#editUserForm input[name="RealName"]').val(userData.realName);

                    // 确保编辑弹窗的角色选择器也加载了角色数据
                    var editRoleSelect = $('#editRoleSelect');
                    if (editRoleSelect.find('option').length <= 1) {
                        // 如果角色选择器没有数据，重新加载
                        $.ajax({
                            url: '@Url.Action("GetRoles", "Account")',
                            type: 'GET',
                            success: function (res) {
                                if (res.success) {
                                    editRoleSelect.empty();
                                    editRoleSelect.append('<option value="">请选择角色</option>');
                                    res.data.forEach(function (role) {
                                        editRoleSelect.append('<option value="' + role.id + '">' + role.roleName + '</option>');
                                    });

                                    // 设置角色选择
                                    if (userData.roleIds && userData.roleIds.length > 0) {
                                        var roleId = userData.roleIds[0];
                                        editRoleSelect.val(roleId);
                                    } else if (userData.roleName && userData.roleName.length > 0) {
                                        editRoleSelect.val('');
                                    }

                                    layui.form.render('select');
                                }
                            }
                        });
                    } else {
                        // 如果已有数据，直接设置
                        if (userData.roleIds && userData.roleIds.length > 0) {
                            var roleId = userData.roleIds[0];
                            editRoleSelect.val(roleId);
                        } else if (userData.roleName && userData.roleName.length > 0) {
                            editRoleSelect.val('');
                        }
                    }

                    // 重新渲染表单
                    layui.form.render();

                    // 确保弹窗内容可以交互，但密码字段保持只读
                    $(layero).find('input:not([name="Pwd"]), select, button').prop('disabled', false);
                    $(layero).find('input[name="Pwd"]').prop('readonly', true).css({
                        'background-color': '#f5f5f5',
                        'color': '#999',
                        'cursor': 'not-allowed'
                    });

                    // 阻止事件冒泡
                    $(layero).on('click', function (e) {
                        e.stopPropagation();
                    });

                    // 防止密码字段被修改
                    $(layero).find('input[name="Pwd"]').on('input keydown keyup keypress paste', function (e) {
                        e.preventDefault();
                        e.stopPropagation();
                        return false;
                    });

                    // 绑定更新按钮事件
                    $(layero).find('button[lay-submit]').on('click', function (e) {
                        e.preventDefault();
                        e.stopPropagation();
                        handleEditFormSubmit();
                    });

                    // 绑定编辑重置按钮事件
                    $(layero).find('#editResetBtn').on('click', function (e) {
                        e.preventDefault();
                        e.stopPropagation();
                        // 重新填充表单数据
                        $('#editUserId').val(userData.id);
                        $('#editUserForm input[name="Name"]').val(userData.name);
                        $('#editUserForm input[name="Pwd"]').val('********');
                        $('#realPassword').val(userData.pwd);
                        $('#editUserForm input[name="RealName"]').val(userData.realName);
                        if (userData.roleIds && userData.roleIds.length > 0) {
                            var roleId = userData.roleIds[0];
                            $('#editRoleSelect').val(roleId);
                        } else if (userData.roleName && userData.roleName.length > 0) {
                            $('#editRoleSelect').val('');
                        }
                        // 清除验证消息
                        $('.layui-form-msg, .layui-form-danger, .layui-text-danger').remove();
                        layui.form.render();
                        // 确保重置后密码字段仍然不可编辑
                        $(layero).find('input[name="Pwd"]').prop('readonly', true).css({
                            'background-color': '#f5f5f5',
                            'color': '#999',
                            'cursor': 'not-allowed'
                        });
                        layui.layer.msg('表单已重置', { icon: 1 });
                    });

                    // 聚焦到第一个输入框
                    setTimeout(function () {
                        $('#editUserForm input[name="Name"]').focus();
                    }, 100);
                },
                end: function () {
                    // 弹窗关闭后清空表单
                    $('#editUserForm')[0].reset();
                    // 清除所有验证消息
                    $('.layui-form-msg, .layui-form-danger, .layui-text-danger').remove();
                    layui.form.render();
                }
            });
        }

        // 处理编辑表单提交
        function handleEditFormSubmit() {
            // 获取表单数据
            var formData = {
                Id: $('#editUserId').val(),
                Name: $('#editUserForm input[name="Name"]').val().trim(),
                Pwd: $('#realPassword').val(), // 从隐藏字段获取真实密码
                RealName: $('#editUserForm input[name="RealName"]').val().trim(),
                RoleIds: $('#editRoleSelect').val()
            };

            // 验证表单数据
            if (!formData.Name) {
                layui.layer.msg('请输入用户名', { icon: 2 });
                $('#editUserForm input[name="Name"]').focus();
                return;
            }
            if (!formData.Pwd) {
                layui.layer.msg('密码不能为空', { icon: 2 });
                return;
            }
            if (!formData.RealName) {
                layui.layer.msg('请输入真实姓名', { icon: 2 });
                $('#editUserForm input[name="RealName"]').focus();
                return;
            }
            if (!formData.RoleIds) {
                layui.layer.msg('请选择角色', { icon: 2 });
                $('#editRoleSelect').focus();
                return;
            }

            // 处理roleId，将字符串转换为数组
            var roleId = [];
            if (formData.RoleIds) {
                roleId.push(parseInt(formData.RoleIds));
            }

            // 构建提交数据 - 根据API文档，参数名应该是小写
            var submitData = {
                accountId: parseInt(formData.Id),
                name: formData.Name,
                pwd: formData.Pwd, // 发送真实密码
                realName: formData.RealName,
                roleId: roleId
            };

            var loadIndex = layui.layer.load(1, {
                shade: [0.1, '#fff']
            });

            $.ajax({
                url: '@Url.Action("UpdateUser", "Account")',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(submitData),
                success: function (res) {
                    layui.layer.close(loadIndex);

                    if (res.success) {
                        layui.layer.msg(res.message, { icon: 1 });
                        layui.layer.closeAll();
                        // 重新加载表格数据
                        layui.table.reload('userTable');
                    } else {
                        layui.layer.msg(res.message || '更新失败', { icon: 2 });
                    }
                },
                error: function (xhr, status, error) {
                    layui.layer.close(loadIndex);
                    console.error('更新失败:', xhr.responseText);
                    console.error('状态码:', xhr.status);
                    console.error('错误信息:', error);

                    var errorMsg = '网络错误，请稍后重试';
                    try {
                        var errorResponse = JSON.parse(xhr.responseText);
                        if (errorResponse.message) {
                            errorMsg = errorResponse.message;
                        }
                    } catch (e) {
                        // 如果解析失败，使用默认错误信息
                    }

                    layui.layer.msg(errorMsg, { icon: 2 });
                }
            });
        }

        // 删除用户
        function deleteUser(userId) {
            // 确保userId是数字类型
            if (typeof userId === 'string') {
                userId = parseInt(userId);
            }

            layui.layer.confirm('确定要删除这个用户吗？', {
                shade: false, // 移除遮罩层
                shadeClose: false,
                title: '确认删除'
            }, function (index) {
                layui.layer.close(index);

                var loadIndex = layui.layer.load(1, {
                    shade: [0.1, '#fff']
                });

                $.ajax({
                    url: '@Url.Action("DeleteUser", "Account")',
                    type: 'POST',
                    data: { userId: userId },
                    success: function (res) {
                        layui.layer.close(loadIndex);

                        if (res.success) {
                            layui.layer.msg(res.message, { icon: 1 });
                            layui.table.reload('userTable');
                        } else {
                            layui.layer.msg(res.message || '删除失败', { icon: 2 });
                        }
                    },
                    error: function (xhr, status, error) {
                        layui.layer.close(loadIndex);
                        console.error('删除失败:', xhr.responseText);

                        var errorMsg = '删除失败，请稍后重试';
                        try {
                            var errorResponse = JSON.parse(xhr.responseText);
                            if (errorResponse.message) {
                                errorMsg = errorResponse.message;
                            }
                        } catch (e) {
                            // 如果解析失败，使用默认错误信息
                        }

                        layui.layer.msg(errorMsg, { icon: 2 });
                    }
                });
            });
        }

        // 页面加载完成后初始化
        $(document).ready(function () {
            console.log('页面加载完成');

            // 清除所有验证消息
            $('.layui-form-msg, .layui-form-danger, .layui-text-danger').remove();

            // 添加快捷键支持
            $(document).keydown(function (e) {
                // ESC键关闭所有弹窗
                if (e.keyCode === 27) {
                    layui.layer.closeAll();
                }
            });

            // 通用按钮监听
            $(document).on('click', 'button', function (e) {
                var $btn = $(this);
                if ($btn.hasClass('layui-btn') && $btn.attr('lay-submit')) {
                    e.stopPropagation();
                    e.preventDefault();

                    // 尝试调用Layui内部的函数
                    if (typeof handleFormSubmitDirect === 'function') {
                        handleFormSubmitDirect();
                    } else {
                        handleFormSubmitDirectFallback();
                    }
                }
            });
        });





        // 外部事件监听
        $(document).on('click', '.layui-btn[lay-submit]', function (e) {
            e.stopPropagation();
            e.preventDefault();

            // 尝试调用Layui内部的函数
            if (typeof handleFormSubmitDirect === 'function') {
                handleFormSubmitDirect();
            } else {
                handleFormSubmitDirectFallback();
            }
        });

        // 处理表单提交的备用函数
        function handleFormSubmitDirectFallback() {
            // 获取表单数据
            var formData = {
                Name: $('#addUserForm input[name="Name"]').val().trim(),
                Pwd: $('#addUserForm input[name="Pwd"]').val().trim(),
                RealName: $('#addUserForm input[name="RealName"]').val().trim(),
                RoleIds: $('#addUserForm select[name="RoleIds"]').val()
            };

            // 验证表单数据
            if (!formData.Name) {
                layui.layer.msg('请输入用户名', { icon: 2 });
                $('#addUserForm input[name="Name"]').focus();
                return;
            }
            if (!formData.Pwd) {
                layui.layer.msg('请输入密码', { icon: 2 });
                $('#addUserForm input[name="Pwd"]').focus();
                return;
            }
            if (!formData.RealName) {
                layui.layer.msg('请输入真实姓名', { icon: 2 });
                $('#addUserForm input[name="RealName"]').focus();
                return;
            }
            if (!formData.RoleIds) {
                layui.layer.msg('请选择角色', { icon: 2 });
                $('#addUserForm select[name="RoleIds"]').focus();
                return;
            }

            // 处理roleId，将字符串转换为数组
            var roleId = [];
            if (formData.RoleIds) {
                roleId.push(parseInt(formData.RoleIds));
            }

            // 构建提交数据 - 根据API文档，参数名应该是小写
            var submitData = {
                name: formData.Name,
                pwd: formData.Pwd,
                realName: formData.RealName,
                roleId: roleId
            };

            var loadIndex = layui.layer.load(1, {
                shade: [0.1, '#fff']
            });

            $.ajax({
                url: '@Url.Action("AddUser", "Account")',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(submitData),
                success: function (res) {
                    layui.layer.close(loadIndex);

                    if (res.success) {
                        layui.layer.msg(res.message, { icon: 1 });
                        layui.layer.closeAll();
                        // 重新加载表格数据
                        layui.table.reload('userTable');
                    } else {
                        layui.layer.msg(res.message || '添加失败', { icon: 2 });
                    }
                },
                error: function (xhr, status, error) {
                    layui.layer.close(loadIndex);
                    console.error('提交失败:', xhr.responseText);
                    console.error('状态码:', xhr.status);
                    console.error('错误信息:', error);

                    var errorMsg = '网络错误，请稍后重试';
                    try {
                        var errorResponse = JSON.parse(xhr.responseText);
                        if (errorResponse.message) {
                            errorMsg = errorResponse.message;
                        }
                    } catch (e) {
                        // 如果解析失败，使用默认错误信息
                    }

                    layui.layer.msg(errorMsg, { icon: 2 });
                }
            });
        }


    </script>
}
